#region

using System;
using System.Collections.Generic;
using System.Linq;
using TimeDRODPOF.TDLib;
using VeeTileEngine2012;

#endregion

namespace TimeDRODPOF.TDComponents
{
    public class TDCTarget : Component
    {
        public TDCTarget(params string[] mTargetTags) { TargetTags = mTargetTags; }

        public Entity Target { get; set; }
        public int TargetDistance { get; set; }
        public int TargetNextX { get; set; }
        public int TargetNextY { get; set; }
        public string[] TargetTags { get; set; }

        private void GetNearestTarget(IEnumerable<string> mTargetTags)
        {
            Target = null;

            var targetEntities =
                new SortedSet<Entity>(new ByDistance((x1, y1, x2, y2) => TDLHelper.ChebyshevDistance(x1, y1, x2, y2),
                                                     X, Y));

            foreach (var tag in mTargetTags)
            {
                var entities = Field.GetEntitiesByTag(tag);
                if (entities == null) continue;

                foreach (var ent in entities) targetEntities.Add(ent);
            }

            if (targetEntities.Count == 0) return;

            var target = targetEntities.First();

            if (targetEntities.Count == 1)
            {
                Target = target;
                TargetDistance = TDLHelper.ChebyshevDistance(target.X, target.Y, X, Y);
                return;
            }

            if (targetEntities.Contains(Entity)) targetEntities.Remove(Entity);

            if (targetEntities.Count > 1)
            {
                Target = target;
                TargetDistance = TDLHelper.ChebyshevDistance(target.X, target.Y, X, Y);
            }
        }

        public override void NextTurn(object mInput)
        {
            base.NextTurn(mInput);
            GetNearestTarget(TargetTags);

            if (Target == null) return;

            TargetNextX = TargetNextY = 0;
            if (Target.X > X) TargetNextX = 1;
            else if (Target.X < X) TargetNextX = -1;
            if (Target.Y > Y) TargetNextY = 1;
            else if (Target.Y < Y) TargetNextY = -1;
        }
    }
}